package com.data.analysislib

import android.app.Application
import com.data.analysislib.event.IAnalyticsEvent
import com.data.analysislib.util.AdjustUtil
import com.data.analysislib.util.AdvertIdUtil
import com.data.analysislib.util.FacebookUtil
import com.data.analysislib.util.GoogleInstallUtil

object AnalyticsUtil {

    fun init(
        context: Application,
        gpReferrerCallback: (String) -> Unit,
        adIdCallback: (String) -> Unit
    ) {
        GoogleInstallUtil.init(context) {
            gpReferrerCallback.invoke(it)
            saveGoogleInstallInfo()
        }

        AdvertIdUtil.init(context) { _, _ ->
            adIdCallback.invoke(getAdId())
            saveGoogleInstallInfo()
        }

        AdjustUtil.init(context)

        FacebookUtil.init(context)
    }


    fun addEvent(event: IAnalyticsEvent) {
        AdjustUtil.addEvent(event)
        FacebookUtil.addEvent(event)
    }

    fun addApplyEvent() {
        AdjustUtil.addEvent(IAnalyticsEvent.AT_LOAN_APPLY)
        FacebookUtil.addEvent(IAnalyticsEvent.AT_LOAN_APPLY)
    }


    fun addRegisterEvent() {
        AdjustUtil.addEvent(IAnalyticsEvent.AT_REGISTER)
        FacebookUtil.addEvent(IAnalyticsEvent.AT_REGISTER)
    }

    private fun saveGoogleInstallInfo() {
        GoogleInstallUtil.saveS2sInfo()
    }

    fun getInstallReferrer(): String {
        return GoogleInstallUtil.getInstallReferrer()
    }

    fun getAdId(): String {
        return AdvertIdUtil.getAdId()
    }

    fun getAdEnabled(): Int {
        return AdvertIdUtil.getAdEnabled()
    }

    fun getAndroidId(): String {
        return AdvertIdUtil.getAndroidId()
    }

    fun getOutputParams(): HashMap<String, Any> {
        return HashMap<String, Any>().apply {
            put("androidId", getAndroidId())
            put("aduid", getAdId())
            put("advertId", getAdId())
            put("isLimitAdTrackingEnabled", getAdEnabled())
            put("channelCode", getInstallReferrer())
            put("subChannelCode", getInstallReferrer())
            put("token", AnalysisBuilder.token)
            put("userId", AnalysisBuilder.userId)
        }
    }
}